<template>
  <div>
    <div class="search">
      <input v-model="keyword"  type="text" class="searchinput" placeholder="请输入城市名">
    </div>
    <div class="search-content" v-show="keyword">
      <ul class="search-list">
        <li class="itemlist"  @click="handlechangecity(item.name)"  v-for="item in list" :key="item.id">{{item.name}}</li>
        <li class="itemlist" v-show="hassearch" >没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'citysearch',
  props: {
    citylist: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null,
      nosearchdata: {
        id: 42,
        spell: '数据',
        name: '找不到匹配城市'
      }
    }
  },
  methods: {
    handlechangecity (city) {
      this.$store.commit('changecity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hassearch () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 设置定时器，防止频繁搜索；
      // 循环检索citylist数据中的对象的键spell,naem有无匹配keyword的值
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.citylist) {
          this.citylist[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style scoped>
  .search{
    width: 100%;
    height: 45px;
    background: #00d3d3;
    text-align: center;
  }
  .searchinput{
    width: 90%;
    line-height: 35px;
    padding:0 10px;
    text-align: center;
    color: #787878;
    border: 0;
  }
  .search-content{
    position: absolute;
    z-index: 1;
    top: 95px;
    left: 0;
    bottom: 0;
    right: 0;
    background-color: #f8f8f8;
  }
  .search-list{
    background: #fff;
    list-style: none;
    padding: 0;
    border: 1px solid #eaeaea;
  }
  .itemlist{
    line-height: 28px;
    padding-left: 15px;
    border-bottom: 1px solid #f6f6f6;
  }
</style>
